package com.wang.vedio.fragment.index;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxui.fragment.NewLazyFragment;
import com.youth.banner.Banner;
import com.youth.banner.indicator.CircleIndicator;
import com.youth.banner.listener.OnPageChangeListener;
import com.wang.vedio.R;
import com.wang.vedio.adapter.index.BannerImageAdapter;
import com.wang.vedio.adapter.index.ZuiXinAdapter;
import com.wang.vedio.base.TcWebActivity;
import com.wang.vedio.bean.BannerBean;
import com.wang.vedio.event.MessageEvent;
import com.wang.vedio.net.SharedHelper;
import com.wang.vedio.net.entity.BaseBean;
import com.wang.vedio.net.entity.VideoBean;
import com.wang.vedio.net.rxjava.HttpMethods;
import com.wang.vedio.net.subscribers.ProgressSubscriber;
import com.wang.vedio.net.subscribers.SubscriberOnNextListener;
import com.wang.vedio.player.PlayerActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 描述：工作动态
 */
public class ZuiXinFragment extends NewLazyFragment implements BaseQuickAdapter.OnItemClickListener {
    @BindView(R.id.rec_main)
    RecyclerView recMain;
    @BindView(R.id.srl_all)
    SmartRefreshLayout srlAll;
    @BindView(R.id.banner)
    Banner mBanner;
    @BindView(R.id.bannerTitle)
    TextView bannerTitle;

    private int type;
    Unbinder unbinder;

    private ZuiXinAdapter mAdapter;

    private ArrayList<BannerBean> mBannerList = new ArrayList<>();
    private BannerImageAdapter bannerImageAdapter;

    @Override
    protected int getContentViewId() {
        return R.layout.gyss_fragment_index_gzdt_layout;
    }

    @Override
    protected void initView(View view) {
        unbinder = ButterKnife.bind(this, view);
        init();
        initSrl();
        super.initView(view);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshData(MessageEvent messageEvent) {
//        if (messageEvent.getTag().equals(EventTag.DT)) {
//            refresh();
//        }
    }

    public void refresh() {
        isShowDialog = false;
        page = 1;
        mList.clear();
        getData();
    }


    private void initSrl() {
        srlAll.setEnableRefresh(true);
        srlAll.setEnableLoadMore(true);
        srlAll.setOnRefreshListener(refresh_layout -> {
            refresh();
        });

        srlAll.setOnLoadMoreListener(refreshLayout -> {
            page ++;
            getData();
        });
    }

    private List<VideoBean> mList;


    private void init() {
        mList = new ArrayList<>();
        ((SimpleItemAnimator) recMain.getItemAnimator()).setSupportsChangeAnimations(false);
        LinearLayoutManager gridLayoutManager = new LinearLayoutManager(mContext);

        recMain.setLayoutManager(gridLayoutManager);
        mAdapter = new ZuiXinAdapter(R.layout.item_zuixin_video,mList);
        recMain.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Bundle bundle = new Bundle();
                bundle.putSerializable("obj",mList.get(position));
                RxActivityTool.skipActivity(mContext, PlayerActivity.class,bundle);
                getVedioById(mList.get(position).getId());
            }
        });
    }

    private void getVedioById(String vedioId){
        
        SubscriberOnNextListener<BaseBean<VideoBean>> onNextListener = baseBean -> {
            
            Bundle bundle = new Bundle();
            bundle.putSerializable("obj",baseBean.getData());
            RxActivityTool.skipActivity(mContext,PlayerActivity.class,bundle);
        };
        Map<String,Object> params = new HashMap<>();
        params.put("id",vedioId);
        params.put("memberId", SharedHelper.readId(mContext));
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), new Gson().toJson(params));
        HttpMethods.getInstance().getVedioById(new ProgressSubscriber<>(onNextListener, mContext, false), requestBody);
    }

    private void initBanner() {
        bannerImageAdapter = new BannerImageAdapter(mBannerList);
        bannerTitle.setText(mBannerList.get(0).getTitle());
        mBanner.setAdapter(bannerImageAdapter).addBannerLifecycleObserver(this)//添加生命周期观察者
                .setIndicator(new CircleIndicator(mContext))//设置指示器
                .setBannerRound(20)
                .setOnBannerListener((data, position) -> {
                    //广告
                    Bundle bundle = new Bundle();
                    bundle.putString("title",mBannerList.get(position).getTitle());
                    bundle.putString("url",mBannerList.get(position).getAdPath());
                    Log.i("URLXXX",mBannerList.get(position).getAdPath());
                    RxActivityTool.skipActivity(mContext, TcWebActivity.class,bundle);
                })
                .addOnPageChangeListener(new OnPageChangeListener() {
                    @Override
                    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                    }

                    @Override
                    public void onPageSelected(int position) {
                        bannerTitle.setText(mBannerList.get(position).getTitle());
                    }

                    @Override
                    public void onPageScrollStateChanged(int state) {

                    }
                })
                .start();
    }

    private int page = 1;
    private boolean isShowDialog = true;

    @Override
    protected void initData() {
        getBanner();
        refresh();
    }

    @Override
    public void onResume() {
        super.onResume();
    }


    private void getBanner(){
        
        SubscriberOnNextListener<BaseBean<List<BannerBean>>> onNextListener = baseBean -> {
            
            mBannerList.clear();
            mBannerList.addAll(baseBean.getData());
            initBanner();
        };
        Map<String,Object> params = new HashMap<>();
        params.put("adCode","tuiJianBanner");
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), new Gson().toJson(params));
        HttpMethods.getInstance().getBannerByCode(new ProgressSubscriber<>(onNextListener, mContext, false), requestBody);
    }

    private void getData(){
        
        mAdapter.notifyDataSetChanged();
        SubscriberOnNextListener<BaseBean<List<VideoBean>>> onNextListener = baseBean -> {
            
            if (srlAll != null) {
                srlAll.finishLoadMore();
                srlAll.finishRefresh();
            }
            mList.addAll(baseBean.getData());
            mAdapter.notifyDataSetChanged();
        };
        if (mList.size() == 0) {
            page = 1;
        }
        Map<String,Object> params = new HashMap<>();
        params.put("pageIndex",page+"");
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), new Gson().toJson(params));
        HttpMethods.getInstance().getZuiXinList(new ProgressSubscriber<>(onNextListener, mContext, false), requestBody);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        unbinder.unbind();
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//
    }
}
